package app;

import java.io.IOException;
import java.security.KeyPair;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import utils.SysInutils;
import db.DBUser;
import db.DBUtils;
import static app.Constants.*;
public class LogonServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		doPost(req, res);
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		String name = req.getParameter("name");
		String password = req.getParameter("password");

		DBUser user = validateLogin(name, password);

		if (user == null) {

			res.getWriter().write("ERR");

		} else {

			HttpSession session = req.getSession();
			KeyPair keys = SysInutils.GerarParChaves();

			String publicKey = SysInutils.PubKeytoString(keys.getPublic());

			session.setAttribute(USER, user);
			session.setAttribute(KEYS, keys);

			res.getWriter().write("publicKey=" + publicKey);

		}

		res.getWriter().close();

	}

	private DBUser validateLogin(String name, String password) {
		// All parameters must be valid
		if (name == null || password == null) {
			return null;
		}

		// Get a user by key
		DBUser user = DBUtils.getUser(name);

		if (user == null) {
			return null;
		}

		// Check if the password is valid
		if (!user.getPass().equals(DBUtils.genPassHash(password.trim()))) {
			return null;
		}

		return user;
	}

}
